package com.cmf.myproject.service.user;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cmf.myproject.dal.mybatis.mapper.UserMapper;
import com.cmf.myproject.dal.mybatis.model.User;
import com.cmf.myproject.dal.mybatis.model.UserExample;
import com.cmf.myproject.dal.mybatis.model.UserExample.Criteria;
import com.cmf.myproject.service.user.dto.UserAddItemReqDto;
import com.cmf.myproject.service.user.dto.UserQueryFilter;
import com.cmf.myproject.service.user.dto.UserUpdateItemReqDto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.system.core.enums.YesOrNoEnum;
import com.system.core.results.ResultBase;
import com.system.core.view.layui.table.TableViewRspDto;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserService {
	
	private SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Autowired
	private UserMapper userMapper;
	
	public List<User> userEnableList(){
		UserExample userExample = new UserExample();
		userExample.createCriteria().andIsLockedEqualTo(YesOrNoEnum.NO);
		return userMapper.selectByExample(userExample);
	}
	
	/**
	 * 页面列表查询
	 * @return TableViewRspDto 返回TableViewRspDto视图对象，符合Layui规范
	 */
	public TableViewRspDto<User> userList(UserQueryFilter filter){
		log.debug("[user]查询入参：{}",filter);
		TableViewRspDto<User> pageResult = new TableViewRspDto<User>();
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		//在此插入查询条件start
		if(filter.getId() != null) {
			criteria.andIdEqualTo(filter.getId());
		}
		if(StringUtils.isNotBlank(filter.getUserName())) {
			criteria.andUserNameEqualTo(filter.getUserName());
		}
		if(StringUtils.isNotBlank(filter.getPassword())) {
			criteria.andPasswordEqualTo(filter.getPassword());
		}
		if(StringUtils.isNotBlank(filter.getNick())) {
			criteria.andNickEqualTo(filter.getNick());
		}
		if(StringUtils.isNotBlank(filter.getPosition())) {
			criteria.andPositionEqualTo(filter.getPosition());
		}
		if(StringUtils.isNotBlank(filter.getPhone())) {
			criteria.andPhoneEqualTo(filter.getPhone());
		}
		if(filter.getIsLocked() != null) {
			criteria.andIsLockedEqualTo(filter.getIsLocked());
		}
		if(filter.getUserRoleId() != null) {
			criteria.andUserRoleIdEqualTo(filter.getUserRoleId());
		}
		if(filter.getPersonStatus() != null) {
			criteria.andPersonStatusEqualTo(filter.getPersonStatus());
		}
		if(filter.getSex() != null) {
			criteria.andSexEqualTo(filter.getSex());
		}
		/**
		 * jdbcType:timestamp
		 */
		try {
			if(StringUtils.isNotBlank(filter.getCreateTimeStrStart())) {
				criteria.andCreateTimeGreaterThanOrEqualTo(timeformat.parse(filter.getCreateTimeStrStart()));
			}
			if(StringUtils.isNotBlank(filter.getCreateTimeStrEnd())) {
				criteria.andCreateTimeLessThanOrEqualTo(timeformat.parse(filter.getCreateTimeStrEnd()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			pageResult.setMessage(e.getMessage());
			return pageResult;
		}
		/**
		 * jdbcType:timestamp
		 */
		try {
			if(StringUtils.isNotBlank(filter.getUpdateTimeStrStart())) {
				criteria.andUpdateTimeGreaterThanOrEqualTo(timeformat.parse(filter.getUpdateTimeStrStart()));
			}
			if(StringUtils.isNotBlank(filter.getUpdateTimeStrEnd())) {
				criteria.andUpdateTimeLessThanOrEqualTo(timeformat.parse(filter.getUpdateTimeStrEnd()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			pageResult.setMessage(e.getMessage());
			return pageResult;
		}
		//在此插入查询条件end
		
		Page<User> page = PageHelper.startPage(filter.getPage(), filter.getLimit());
		example.setOrderByClause("create_time desc");
		pageResult.setData(userMapper.selectByExample(example));
		pageResult.setCount(page.getTotal());
		pageResult.setCode(0);
		pageResult.setMessage("查询成功");
		return pageResult;
	}
	
	/**
	 * 根据主键获取单条数据
	 * @param user 使用user对象的主键属性Id类型是Long
	 */
	public User userGetByPrimaryKey(User user) {
		User result = userMapper.selectByPrimaryKey(user.getId());
		return result;
	}
	
	/**
	 * 根据主键更新数据
	 * @param user 被更新对象（请注意，只更新有值属性）
	 */
	public ResultBase userUpdateByPrimaryKey(UserUpdateItemReqDto userUpdateItemReqDto) {
		ResultBase resultBase = new ResultBase();
		User user = new User();
		BeanUtils.copyProperties(userUpdateItemReqDto, user);
		
		if(StringUtils.isNotBlank(userUpdateItemReqDto.getPassword())) {
			user.setPassword(DigestUtils.sha256Hex(userUpdateItemReqDto.getPassword()));
		} else {
			user.setPassword(null);
		}
		
		userMapper.updateByPrimaryKeySelective(user);
		resultBase.setSuccess(true);
		resultBase.setMessage("更新成功");
		return resultBase;
	}
	
	/**
	 * 根据主键删除数据
	 * @param keys 被删除对象主键List集合
	 */
	@Transactional
	public ResultBase userDeleteByPrimaryKey(List<Long> keys) {
		ResultBase resultBase = new ResultBase();
		try {
			keys.forEach((key)->{
				userMapper.deleteByPrimaryKey(key);
			});
		} catch (Exception e) {
			resultBase.setMessage(e.getMessage());
			return resultBase;
		}
		resultBase.setSuccess(true);
		resultBase.setMessage("成功删除"+keys.size()+"条记录");
		return resultBase;
	}
	
	/**
	 * 新增数据
	 * @param userAddItemReqDto 新增对象
	 */
	@Transactional
	public ResultBase userSave(UserAddItemReqDto userAddItemReqDto) {
		ResultBase resultBase = new ResultBase();
		User user = new User();
		BeanUtils.copyProperties(userAddItemReqDto, user);
		user.setPassword(DigestUtils.sha256Hex(userAddItemReqDto.getPassword()));
		userMapper.insertSelective(user);
		resultBase.setSuccess(true);
		resultBase.setMessage("新增成功");
		return resultBase;
	}
	
	public User userFindByName(String userName) {
		//DigestUtils.sha256Hex
		UserExample example = new UserExample();
		example.createCriteria().andUserNameEqualTo(userName);
		List<User> users = userMapper.selectByExample(example);
		if(users.size() != 1) {
			return null;
		}
		return users.get(0);
	}
}
